from typing import List, Optional
from ..interfaces import PlatformAdapter, NormalizedContent
from ..vendor.mindspider.media_platform.weibo.client import WeiboClient
from ..vendor.mindspider.media_platform.weibo.field import SearchType


class WeiboAdapter(PlatformAdapter):
    def __init__(self, headers: Optional[dict] = None, proxy: Optional[str] = None):
        self.client = WeiboClient(headers=headers or {}, proxy=proxy)

    async def search_by_keywords(self, keywords: List[str], time_start: Optional[str], time_end: Optional[str]) -> List[NormalizedContent]:
        items: List[NormalizedContent] = []
        for kw in keywords:
            data = await self.client.get_note_by_keyword(kw, page=1, search_type=SearchType.DEFAULT)
            cards = data.get('cards') or []
            for c in cards:
                mblog = c.get('mblog') or {}
                mid = str(mblog.get('id') or '')
                text = mblog.get('text_raw') or mblog.get('text') or ''
                author = (mblog.get('user') or {}).get('screen_name')
                url = f"https://m.weibo.cn/detail/{mid}" if mid else None
                nc = NormalizedContent(platform='weibo', content_id=mid, author=author, title=None, text=text, url=url, published_at=None, metrics={}, raw=mblog)
                items.append(nc)
        return items

    async def fetch_by_accounts(self, accounts: List[str], time_start: Optional[str], time_end: Optional[str]) -> List[NormalizedContent]:
        items: List[NormalizedContent] = []
        for acc in accounts:
            try:
                cinfo = await self.client.get_creator_container_info(acc)
                lfid = cinfo.get('lfid_container_id') or ''
                if not lfid:
                    continue
                notes = await self.client.get_all_notes_by_creator_id(acc, lfid, crawl_interval=0.5)
                for c in notes:
                    mblog = c.get('mblog') or {}
                    mid = str(mblog.get('id') or '')
                    text = mblog.get('text_raw') or mblog.get('text') or ''
                    author = (mblog.get('user') or {}).get('screen_name')
                    url = f"https://m.weibo.cn/detail/{mid}" if mid else None
                    items.append(NormalizedContent(platform='weibo', content_id=mid, author=author, title=None, text=text, url=url, published_at=None, metrics={}, raw=mblog))
            except Exception:
                continue
        return items
